package com.lysj.bhp.api.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lysj.bhp.system.domain.Verify;
import com.lysj.bhp.system.domain.VerifyEmail;
import com.lysj.bhp.system.repository.VerifyEmailRepository;
import com.lysj.bhp.system.repository.VerifyRepository;
import com.lysj.bhp.user.base.UserContent;
import com.lysj.bhp.user.domain.User;
import com.lysj.bhp.util.http.HttpUtil;
import com.lysj.bhp.util.random.RandomUtil;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("api/v2/user")
@Api(value = "UserController", tags = "用户模块接口")
public class ApiUserController extends UserContent {

    @Autowired
    DefaultKaptcha defaultKaptcha;
    @Autowired
    VerifyRepository verifyRepository;
    @Autowired
    VerifyEmailRepository verifyEmailRepository;

    private final long NEXT_SEND_EMAIL = 1000 * 60 * 3;// 发送邮件间隔(15分钟)
    //    private final long NEXT_SEND_EMAIL = 0;// 发送邮件间隔(用于测试)
    private static final long expires = 1000 * 60 * 3;

    @InitBinder
    public void InitBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }


    @ApiOperation(value = "设置初始个人信息", notes = "")
    @PostMapping(value = "/set_info")
    public Resp setInfo(User model) {
        if (currentUser().getInfoStatus() != 0) {
            return new Resp(Resp.PARAM_ERROR, "您已经设置过个人信息了，请不要重复设置");
        }
        currentUser().setPhone(model.getPhone());
        currentUser().setSureName(model.getSureName());
        currentUser().setName(model.getName());
        currentUser().setBirthday(model.getBirthday());
        currentUser().setTwoauthentication(model.getTwoauthentication());
        currentUser().setNewsPushed(model.getNewsPushed());
        currentUser().setInfoStatus(1);
        userRepository.save(currentUser());
        return new Resp("设置个人信息成功!");
    }

    @ApiOperation(value = "修改个人信息", notes = "")
    @PostMapping(value = "/edit_info")
    public Resp editInfo(User model) {
        currentUser().setPhone(model.getPhone());
        currentUser().setBirthday(model.getBirthday());
        currentUser().setName(model.getName());
        userRepository.save(currentUser());
        return new Resp(currentUser());
    }

    @ApiOperation(value = "修改ERC20", notes = "")
    @PostMapping(value = "/set_erc20")
    public Resp setERC20(User model) {
        if (!ParamUtil.isBlack(currentUser().getErc20())) {
            return new Resp(Resp.PARAM_ERROR, "您已经有ERC-20地址，请不要重复设置");
        }
        if (ParamUtil.isBlack(model.getErc20())) {
            return new Resp(Resp.PARAM_ERROR, "请输入ERC-20地址");
        }
        if (!model.getErc20().startsWith("0x")) {
            return new Resp(Resp.PARAM_ERROR, "请输入以0x开头的地址");
        }
        currentUser().setErc20(model.getErc20());
        userRepository.save(currentUser());
        return new Resp("填写ERC20地址成功!");
    }


    @ApiOperation(value = "修改密码", notes = "")
    @ApiImplicitParam(name = "password", value = "新的密码", required = true, paramType = "query", dataType = "String")
    @PostMapping(value = "/edit_password")
    public Resp editPassword(String oldPassword, String password) {
        if (ParamUtil.isBlack(oldPassword)) {
            return new Resp(Resp.PARAM_ERROR, "请输入旧密码!");
        }
        if (!ParamUtil.md5(oldPassword).equalsIgnoreCase(currentUser().getPassword())) {
            return new Resp(Resp.PARAM_ERROR, "旧密码错误!");
        }
        if (ParamUtil.isBlack(password)) {
            return new Resp(Resp.PARAM_ERROR, "请输入新密码!");
        }
        currentUser().setPassword(ParamUtil.md5(password));
        currentUser().setExpires(System.currentTimeMillis());//使原先的token失效
        userRepository.save(currentUser());
        return new Resp("修改密码成功,请重新登录!");
    }



    @ApiOperation(value = "获取邮箱验证码")
    @ApiImplicitParam(name = "verify", value = "图形验证码", required = true, paramType = "query", dataType = "String")
    @PostMapping(value = "/fetch_my_email_verify_code")
    public Resp fetchMyEmailVerifyCode(String verify) {
        if (ParamUtil.isBlack(verify)) {
            return new Resp(Resp.PARAM_ERROR, "验证码错误");
        }
        Verify verifyQuery = verifyRepository.findOne(currentUser().getEmail());
        if (verifyQuery == null) {
            return new Resp(Resp.PARAM_ERROR, "验证码错误");
        }
        if (!verify.equalsIgnoreCase(verifyQuery.getVerify())) {
            return new Resp(Resp.PARAM_ERROR, "验证码错误");
        }

        VerifyEmail verifyEmailQuery=verifyEmailRepository.findOne(currentUser().getEmail());
        if (System.currentTimeMillis() < verifyEmailQuery.getNextSendEmailMs()) {
            return new Resp(Resp.PARAM_ERROR, "您的操作太频繁,请稍后再进行操作");
        }

        VerifyEmail verifyEmail = new VerifyEmail();
        verifyEmail.setEmail(currentUser().getEmail());
        verifyEmail.setExpires(System.currentTimeMillis() + VerifyEmailRepository.EXPIRE);
        verifyEmail.setVerify(RandomUtil.getRandomString(5));
        verifyEmail.setNextSendEmailMs(System.currentTimeMillis() + NEXT_SEND_EMAIL);// 设置下次发送邮件的时间
        verifyEmailRepository.save(verifyEmail);
        boolean result = mailService.sendVerifyCodeHtmlMail(verifyEmail.getEmail(), verifyEmail.getVerify());
        if (!result) {
            return new Resp(Resp.PARAM_ERROR, "邮件发送失败,请重试");
        }
        return new Resp("获取邮箱验证码成功");
    }


}
